<?php

namespace app\admin\controller;

use app\common\lib\Util;
use app\common\lib\Wechat;
use think\Controller;

class WechatServiceAccountManage extends Controller
{
    protected $token = 'astrlog';//填写你设定的key
    protected $appID = 'wx275e0cf29b3f072e';//填写高级调用功能的app id, 请在微信开发模式后台查询
    protected $appsecret = '2f602b14cf51d20fc50a219ad7a457de';//填写高级调用功能的密钥
    protected $encodingaeskey = 'eWQa2BsQCiNWiysLqTBtlGH8nACNgJZNRZLnhoLMEOH';//填写加密用的EncodingAESKey
    protected $accessToken;
    protected $wechatModel;

    public function _initialize()
    {
        $options = array(
            'token' => $this->token,
            'encodingaeskey' => $this->encodingaeskey,
            'appid' => $this->appID,
            'appsecret' => $this->appsecret
        );
        $this->wechatModel = new Wechat($options); //创建实例对象
        $this->accessToken = $this->wechatModel->checkAuth($this->appID, $this->appsecret);
    }
    ####################################################    相关主动处理接口   ################################################################

    /**
     * 获取模板列表
     */
    public function getTemplateMsg()
    {
        $list = Util::curlRequest('GET', "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={$this->accessToken}");
        $list = $list ? json_decode($list, true) : [];
    }

    /**
     * 发送模板消息
     * @param string $openid
     * @param string $url
     */
    public function sendTemplateMsg(string $openid, $url = '')
    {
        $data = [
            "touser" => $openid,//用户openid
            "template_id" => "EFQu_EBZdl5j5anOFO6PkUqFLrLt9McgnSDkMXzod4g",//todo 模板id
            "url" => $url,//模板跳转地址
            "topcolor" => "#FF0000",
            //模板变量数据
            "data" => [
                "first" => [
                    "value" => "准了科技！110",
                    "color" => "#173177"
                ],
                "keyword1" => [
                    "value" => "定制报告！119",
                    "color" => "#173177"
                ]
            ]
        ];
        $re1 = $this->wechatModel->sendTemplateMessage($data);
    }

    /**
     * 上传永久素材
     */
    public function uploadForeverMedia()
    {
        $filepath = ROOT_PATH . 'public/zhunle_wechat.jpeg';
        return $this->wechatModel->uploadForeverMedia(['media' => $filepath], 'image');
    }
}